<template>
  <div>
    <Drawer
      width="50%"
      title="应用订阅授权"
      placement="right"
      v-model:visible="visible"
      :footer-style="{ textAlign: 'right' }"
      @close="onClose"
    >
      <template #closeIcon>
        <arrow-left-outlined />
      </template>
      <template v-if="dataSource && dataSource.length !== 0">
        <TypographyTitle :level="5">已授权应用套餐</TypographyTitle>
        <Table
          :bordered="true"
          :dataSource="dataSource"
          :columns="authColumns"
          :pagination="false"
          :loading="loading"
          :scroll="scroll"
          class="main-table"
        ></Table>
        <br />
        <Pagination
          show-size-changer
          v-model:current="current"
          v-model:pageSize="pageSize"
          :total="total"
          :show-total="(total) => `共 ${total} 条`"
          @showSizeChange="onShowSizeChange"
        />
        <br />
        <Divider v-if="dataSource && dataSource.length !== 0" />
      </template>
      <TypographyTitle :level="5">授权应用套餐</TypographyTitle>
      <Card>
        <Form ref="formRef" name="dynamic_form_nest_item" :model="formState">
          <Space
            v-for="(item, index) in formState.appPackageAuthList"
            :key="item.id"
            style="display: flex; margin-bottom: 8px"
            align="baseline"
          >
            <FormItem
              :name="['appPackageAuthList', index, 'appId']"
              label="应用"
              :rules="{
                required: true,
                message: '请选择应用',
              }"
            >
              <Select
                v-model:value="item.appId"
                :options="appOpt"
                style="width: 200px"
                placeholder="请选择"
                @change="(value) => changeApp(value, index)"
              ></Select>
            </FormItem>
            <FormItem
              label="套餐"
              :name="['appPackageAuthList', index, 'packageIdList']"
              :rules="{
                required: true,
                message: '请选择套餐',
              }"
            >
              <Select
                v-model:value="item.packageIdList"
                :disabled="disabled"
                mode="multiple"
                placeholder="请选择"
                :options="packageOpt"
                style="width: 200px"
              />
            </FormItem>
            <FormItem
              label="截止时间"
              :name="['appPackageAuthList', index, 'expireTime']"
              :rules="{
                required: true,
                message: '请选择截止时间',
              }"
            >
              <DatePicker
                v-model:value="item.expireTime"
                style="width: 250px"
                :disabled-date="disabledDate"
                :showToday="false"
                placeholder="请选择"
              />
            </FormItem>
            <MinusCircleOutlined @click="removeSight(item)" />
          </Space>
          <div style="margin-left: 606px">
            <FormItem>
              <Button type="dashed" block @click="addSight" style="width: 252px">
                <PlusOutlined />
                添加可订阅应用套餐
              </Button>
            </FormItem>
          </div>
        </Form>
      </Card>
      <template #footer>
        <Button style="margin-right: 8px" type="primary" @click="submit">提交</Button>
        <Button @click="onClose">取消</Button>
      </template>
    </Drawer>
  </div>
</template>
<script lang="ts" setup>
import { ref, watch } from 'vue';
import { ArrowLeftOutlined, PlusOutlined, MinusCircleOutlined } from '@ant-design/icons-vue';
import {
  Form,
  Card,
  FormItem,
  Button,
  Select,
  Drawer,
  Divider,
  Space,
  DatePicker,
  message,
  Table,
  TypographyTitle,
  Pagination,
} from 'ant-design-vue';
import {
  getAppAuthTable,
  getBusinessAppOpt,
  getPackagesOpt,
} from '/@/api/tenant-mgmt/enterpriseAppAuth/enterpriseAppAuth';
import { AuthEntMgtParam } from '/@/api/tenant-mgmt/enterpriseManagement/model/enterpriseManagementModel';
import { authEntMgt } from '/@/api/tenant-mgmt/enterpriseManagement/enterpriseManagement';
import dayjs, { Dayjs } from 'dayjs';
import { AppAuthTableParams } from '/@/api/tenant-mgmt/enterpriseAppAuth/model/enterpriseAppAuthModel';
import { authColumns } from '/@/views/tenant-center/enterpriseManagement/data';
const visible = ref(false);
const loading = ref(true);
const scroll = ref<undefined | object>(undefined);
const dataSource = ref();
let current = ref(1);
const total = ref<number>(0);
const pageSize = ref(5);
const formState = ref({} as AuthEntMgtParam);
let params = {} as AppAuthTableParams;
const disabledDate = (current: Dayjs) => {
  return current && current < dayjs().endOf('day');
};
const getDataSource = async () => {
  try {
    let data = await getAppAuthTable(params);
    dataSource.value = data.items;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
};

const onShowSizeChange = (current: number, pageSize: number) => {
  params.size = pageSize;
  params.current = current;
  getDataSource();
};
watch(pageSize, (val) => {
  if (val > 10) {
    scroll.value = { y: 500 };
  }
  if (val <= 10) {
    scroll.value = undefined;
  }
  params.size = pageSize.value;
});
watch(current, () => {
  params.current = current.value;
  getDataSource();
});

const appOpt = ref();
const packageOpt = ref();
const disabled = ref(true);
const tenantType = ref();
const addSight = () => {
  formState.value.appPackageAuthList.push({
    appId: undefined,
    packageIdList: undefined,
    expireTime: undefined,
    id: Date.now(),
  });
};
const openAuth = async (record) => {
  pageSize.value = 5;
  formState.value.tenantId = record.id;
  params.tenantId = record.id;
  tenantType.value = record.type;
  params.size = pageSize.value;
  params.current = current.value;
  getDataSource();
  formState.value.appPackageAuthList = [];
  addSight();
  appOpt.value = await getBusinessAppOpt();
  visible.value = true;
};
const changeApp = async (value, index) => {
  if (value) {
    disabled.value = false;
    formState.value.appPackageAuthList[index].packageIdList = [];
    packageOpt.value = await getPackagesOpt(value);
  } else {
    formState.value.appPackageAuthList[index].packageIdList = [];
    disabled.value = true;
  }
};
const formRef = ref();

const removeSight = (item) => {
  let index = formState.value.appPackageAuthList.indexOf(item);
  if (index !== -1) {
    formState.value.appPackageAuthList.splice(index, 1);
  }
};

const onClose = () => {
  formState.value = {} as AuthEntMgtParam;
  disabled.value = true;
  visible.value = false;
};
const emit = defineEmits(['get']);
const submit = () => {
  let appPackageAuthList = [];
  formRef.value.validate().then(async () => {
    formState.value.appPackageAuthList.forEach((item) => {
      appPackageAuthList.push({
        appId: item.appId,
        packageIdList: item.packageIdList,
        expireTime: dayjs(item.expireTime).endOf('date').format('YYYY-MM-DD HH:mm:ss'),
      });
    });
    let params = {
      tenantId: formState.value.tenantId,
      appPackageAuthList,
    };
    const res = await authEntMgt(params);
    if (res) {
      message.success('授权成功');
    }
    emit('get');
    onClose();
  });
};
defineExpose({ openAuth });
</script>
